<template>
  <div class="log_bg">
    <div class="top">
      <div class="logo">
        <a href="#" @click.prevent="toIndex()"
          ><img src="@/assets/images/logo.png"
        /></a>
      </div>
    </div>
    <div class="regist">
      <div class="log_img">
        <img src="@/assets/images/l_img.png" width="611" height="425" />
      </div>
      <div class="reg_c">
        <form @submit.prevent="handleRegister">
          <table
            border="0"
            style="width: 420px; font-size: 14px; margin-top: 20px"
            cellspacing="0"
            cellpadding="0"
          >
            <tr height="50" valign="top">
              <td width="95">&nbsp;</td>
              <td>
                <span class="fl" style="font-size: 24px">注册</span>
                <span class="fr"
                  >已有商城账号，<a
                    href="#"
                    style="color: #ff4e00"
                    @click.prevent="toLogin()"
                    >我要登录</a
                  ></span
                >
              </td>
            </tr>
            <!-- 用户名 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;用户名 &nbsp;
              </td>
              <td>
                <input
                  type="text"
                  v-model="user.loginName"
                  @blur="checkLoginName"
                  class="l_user"
                  placeholder="请输入登录名"
                />
              </td>
            </tr>
            <!-- 用户名重复提示（保留，与blur校验呼应） -->
            <tr v-if="isloginNameError">
              <td colspan="2" style="color: red">
                <span>用户名重复</span>
              </td>
            </tr>
            <!-- 昵称 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;昵称 &nbsp;
              </td>
              <td>
                <input
                  type="text"
                  v-model="user.userName"
                  class="l_user"
                  placeholder="请输入用户名"
                />
              </td>
            </tr>
            <!-- 密码 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;密码 &nbsp;
              </td>
              <td>
                <input
                  type="password"
                  v-model="user.password"
                  class="l_pwd"
                  placeholder="请输入密码"
                />
              </td>
            </tr>
            <!-- 确认密码 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;确认密码 &nbsp;
              </td>
              <td>
                <input
                  type="password"
                  v-model="confirmPassword"
                  class="l_pwd"
                  placeholder="请再次输入密码"
                />
              </td>
            </tr>
            <!-- 性别（默认有值，无需额外非空提示） -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;性别 &nbsp;
              </td>
              <td>
                <select v-model="user.sex" class="l_user">
                  <option value="1">男</option>
                  <option value="0">女</option>
                </select>
              </td>
            </tr>
            <!-- 邮箱 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;邮箱 &nbsp;
              </td>
              <td>
                <input
                  type="email"
                  v-model="user.email"
                  class="l_email"
                  placeholder="请输入邮箱"
                />
              </td>
            </tr>
            <!-- 验证码 -->
            <tr height="50">
              <td align="right">
                <font color="#ff4e00">*</font>&nbsp;验证码 &nbsp;
              </td>
              <td>
                <input
                  type="text"
                  v-model="captcha"
                  class="l_ipt"
                  placeholder="请输入验证码"
                />
                <button
                  class="sendCaptcha"
                  @click="sendCaptcha"
                  :disabled="isSendCaptcha"
                  type="button"
                >
                  {{ buttonText }}
                </button>
              </td>
            </tr>
            <!-- 用户协议 -->
            <tr>
              <td>&nbsp;</td>
              <td style="font-size: 12px; padding-top: 20px">
                <span style="font-family: '宋体'" class="fl">
                  <label class="r_rad"
                    ><input type="checkbox" v-model="agreed"
                  /></label>
                  <label class="r_txt">我已阅读并接受《用户协议》</label>
                </span>
              </td>
            </tr>
            <!-- 注册按钮 -->
            <tr height="60">
              <td>&nbsp;</td>
              <td>
                <button type="submit" class="log_btn">立即注册</button>
              </td>
            </tr>
          </table>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import axios from "axios";

export default {
  name: "RegisterView",
  data() {
    return {
      isSendCaptcha: false, //是否已经发送了验证码
      countdown: 60, //倒计时
      timer: null, //计时器对象
      user: {
        loginName: "",
        userName: "",
        password: "",
        sex: 1, // 默认为前台用户（男），无需非空校验
        identityCode: "",
        email: "",
        mobile: "",
        type: 0, // 默认为前台用户
      },
      confirmPassword: "",
      captcha: "",
      agreed: false,
      isloginNameError: false, // 用户名重复标记（与blur校验配合）
    };
  },
  computed: {
    buttonText() {
      return this.isSendCaptcha
        ? `${this.countdown}秒后重新获取`
        : "发送验证码";
    },
  },
  methods: {
    ...mapMutations(["setShowPage"]),
    // 注册提交
    async handleRegister() {
      // 用户名非空校验
      if (!this.user.loginName.trim()) {
        this.$message.error("请输入用户名");
        return;
      }
      // 昵称非空校验
      if (!this.user.userName.trim()) {
        this.$message.error("请输入昵称");
        return;
      }
      // 密码非空校验
      if (!this.user.password.trim()) {
        this.$message.error("请输入密码");
        return;
      }
      // 确认密码非空校验
      if (!this.confirmPassword.trim()) {
        this.$message.error("请输入确认密码");
        return;
      }
      // 邮箱非空校验
      if (!this.user.email.trim()) {
        this.$message.error("请输入邮箱");
        return;
      }
      //校验邮箱格式

      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailRegex.test(this.user.email.trim())) {
        this.$message.error("邮箱格式错误");
        return;
      }
      // 验证码非空校验
      if (!this.captcha.trim()) {
        this.$message.error("请输入验证码");
        return;
      }
      // 用户协议勾选校验
      if (!this.agreed) {
        this.$message.error("请阅读并接受《用户协议》");
        return;
      }
      // 密码一致性校验
      if (this.user.password !== this.confirmPassword) {
        this.$message.error("两次输入的密码不一致");
        return;
      }
      // 用户名重复校验
      if (this.isloginNameError) {
        this.$message.error("用户名已存在，请更换其他用户名");
        return;
      }

      // 校验通过，发起注册请求
      try {
        const response = await axios.post(
          `/api/user/register?captcha=${this.captcha}`,
          this.user
        );
        if (response.data.code === 200) {
          this.$message.success("注册成功");
          this.toLogin(); // 跳转登录页
        }
      } catch (error) {
        this.$message.error(error.message || "注册失败");
      }
    },
    // 发送验证码
    async sendCaptcha() {
      try {
        if (this.isSendCaptcha) return; // 防止重复点击

        // 邮箱非空校验（发送验证码时额外校验，双重保障）
        if (!this.user.email.trim()) {
          this.$message.error("请输入邮箱地址");
          return;
        }
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailRegex.test(this.user.email.trim())) {
          this.$message.error("邮箱格式错误");
          return;
        }

        const response = await axios.get("/api/email/getCaptcha", {
          params: { email: this.user.email },
        });
        if (response.data.code === 200) {
          this.$message.success("验证码已发送");
          this.startCountdown(); // 启动倒计时
        } else {
          this.$message.error(response.data.msg || "验证码发送失败");
        }
      } catch (error) {
        console.error("发送验证码失败:", error);
        this.$message.error("发送验证码失败:" + (error.msg || error.message));
      }
    },
    // 开始倒计时
    startCountdown() {
      if (this.isSendCaptcha) return; // 防止重复触发

      this.isSendCaptcha = true;
      this.countdown = 60;

      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          this.stopCountdown(); // 倒计时结束清理
        }
      }, 1000);
    },
    // 停止倒计时
    stopCountdown() {
      clearInterval(this.timer);
      this.isSendCaptcha = false;
      this.countdown = 60;
    },
    // 组件销毁清理定时器（防止内存泄漏）
    beforeDestroy() {
      this.stopCountdown();
    },
    // 跳转登录页
    toLogin() {
      this.setShowPage(1);
      this.$router.push({ name: "login" });
    },
    // 跳转首页
    toIndex() {
      this.setShowPage(0);
      this.$router.push({ name: "index" });
    },
    // 校验用户名是否重复（失去焦点触发）
    async checkLoginName() {
      const loginName = this.user.loginName.trim();
      if (!loginName) return; // 空值不发起请求

      try {
        const response = await axios.get(
          `/api/user/checkLoginName?loginName=${loginName}`
        );
        this.isloginNameError = response.data.code === 500; // 500代表重复
        if (this.isloginNameError) {
          this.$message.error("用户名已存在，请更换其他用户名");
        }
      } catch (error) {
        this.isloginNameError = true;
        this.$message.error("检查用户名时出错，请稍后重试");
      }
    },
  },
  created() {
    this.$store.commit("setShowPage", 1);
  },
};
</script>

<style>
.sendCaptcha {
  background-color: rgb(252, 87, 14);
  height: 40px;
  width: 120px;
  margin-left: 30px;
  margin-top: 10px;
  color: white;
  border-radius: 5px;
  border: none;
  transition: all 0.2s ease;
}

.sendCaptcha:hover {
  background-color: rgb(230, 78, 10);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.sendCaptcha:active {
  background-color: rgb(200, 68, 0);
  transform: scale(0.98);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
</style>